#!/usr/bin/env python
import dialog
import sys, os
import gst
import gobject
from url_parse import PlaylistParser

home_dir = os.environ['HOME']

from urllib2 import urlopen
from random import choice

#d = dialog.Dialog(dialog='Xdialog', compat='Xdialog')
d = dialog.Dialog(dialog='dialog')
d.add_persistent_args(["--backtitle", "Commandline Webradio Player"])

class WebRadioPlayer():
    def __init__(self):
        self.pipeline = None
        self.playlist_parser = PlaylistParser()
        self.populate()

    def populate(self):
        filename = None
        self.webradios = list()
        config_path = os.path.join(home_dir, '.cwc', 'webradios.txt')
        if os.path.isfile(config_path):
            filename = config_path
        else:
            filename = '../doc/webradios.txt'
        file = open(filename)
        data = file.readlines()
        file.close()
        for line in data:
            if line.find(';') != -1:
                title, url = line.split(';')
                title = title.strip()
                url = url.strip()
                if url.endswith('.pls') or url.endswith('.m3u'):
                    entry = self.playlist_parser.get_entry(url)
                    if entry is not None:
                        self.add_webradio(title, entry)
                else:
                    self.add_webradio(title, url)

    def add_webradio(self, name, uri):
        self.webradios.append({'name': name, 'uri': uri})

    def get_names(self):
        l = list()
        for index, radio in enumerate(self.webradios):
            l.append(('%s|%s' %(index, radio['name']), ""))
        l.append(('Stop playback', ''))
        return l

    def get_radio_by_name(self, name):
        for radio in self.webradios:
            if name.endswith(radio['name']):
                return radio
        return None

    def get_radio_by_id(self, id):
        for index, radio in enumerate(self.webradios):
            if index == id:
                return radio
        return None

    def handle_exit_code(self, d, code):
        if code in (d.DIALOG_CANCEL, d.DIALOG_ESC):
            if code == d.DIALOG_CANCEL:
                msg = "You chose cancel in the last dialog box. Do you want to " \
                      "exit ?"
            else:
                msg = "You pressed ESC in the last dialog box. Do you want to " \
                      "exit ?"
            if d.yesno(msg) == d.DIALOG_OK:
                sys.exit(0)
            return 0
        else:
            return 1 

    def webradio_choice(self, d, autolaunch=None):
        webradios_names = self.get_names()   
        if autolaunch:
            radio = self.get_radio_by_id(int(autolaunch))
            if radio is not None:
                self.play(d, radio['name'], radio['uri']) 

        while 1:
            (code, tag) = d.menu('Choose webradio', choices=webradios_names)
            if self.handle_exit_code(d, code):
                break

        if self.pipeline is not None:
            self.pipeline.set_state(gst.STATE_NULL)
       
        radio = self.get_radio_by_name(tag)
        if radio is not None:
            self.play(d, radio['name'], radio['uri'])
        self.webradio_choice(d)

    def play(self, d, name, uri):
        self.pipeline = p  = gst.parse_launch('souphttpsrc location=%s ! queue2 ! mad ! autoaudiosink' %uri)
        p.set_state(gst.STATE_PLAYING)
        if name != 'Stop playback':
            d.setBackgroundTitle('Playing %s' %name)
        else:
            d.setBackgroundTitle('Playback stopped')
   
    def run(self, autolaunch):
        self.webradio_choice(d, autolaunch)

def main():
    import argparse
    parser = argparse.ArgumentParser(description='Lightweight Webradio player')
    parser.add_argument('--autolaunch', dest='autolaunch', help='number of webradio to launch at start')
    args = parser.parse_args()
    try:
        wrp = WebRadioPlayer()
        gobject.idle_add(wrp.run, args.autolaunch)
        l = gobject.MainLoop().run()
    except dialog.error, exc_instance:
        sys.stderr.write("Error:\n\n%s\n" % exc_instance.complete_message())
        sys.exit(1)

    sys.exit(0)

if __name__ == "__main__": main()

